﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Linq;
using SyncList.Business.ValueObject;

namespace SyncList.Business.Business
{

    /// <summary>
    /// Importer les données
    /// </summary>
    class ImportService : IImportService
    {

        /// <summary>
        /// Importer Xml
        /// </summary>
        /// <param name="fileName">Nom du fichier à importer</param>
        /// <returns></returns>
        public Data ImportXml(string fileName)
        {
            Data data = null;

            if (File.Exists(fileName))
            {
                data = new Data();
                XDocument xDoc = XDocument.Load(fileName);



                var xDefinitions = from xDef in xDoc.Element("SyncList").Descendants("Definition")
                                  select new
                                  {
                                      PathList = xDef.Element("PathList").Descendants("Path").Select(d => d.Value),
                                      MinSize = xDef.Element("Filter").Attribute("MinSize").Value,
                                      Title = xDef.Element("Title").Value
                                  };
                var xDefinition = xDefinitions.FirstOrDefault();
                if (xDefinition != null)
                {
                    data.MinSize = long.Parse(xDefinition.MinSize);
                    data.PathList = xDefinition.PathList.ToList();
                    data.Title = xDefinition.Title;
                }

                IEnumerable<FileDef> xFiles = from xFile in xDoc.Descendants("File")
                             select new FileDef
                             {
                                   Name = (string)xFile.Attribute("name"),
                                   Size = (long)xFile.Attribute("size"),
                                   Hash = (string)xFile.Attribute("hash"),
                                   LocalFolder = (string)xFile.Attribute("folder")
                             };

                foreach (FileDef file in xFiles)
                    data.Files.Add(file);


                File.Copy(fileName, fileName + ".lastimport.bak", true);
            }

            

            return (data);
        }


    }
}
